﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;
using System.Web;

namespace CoolCode.DataSource
{
    public class CacheFactory
    {
        private static ICacheStrategy instance;

        public static ICacheStrategy CreateInstance()
        {
            if (instance == null)
            {
                string typeName = ConfigurationManager.AppSettings["CacheType"];
                string assemblyName = ConfigurationManager.AppSettings["CacheAssembly"];
                if (String.IsNullOrEmpty(typeName) || String.IsNullOrEmpty(assemblyName))
                    return null;
                instance = CreateInstance(typeName, assemblyName);
            }
            return instance;
        }

        public static ICacheStrategy CreateInstance(string typeName, string assemblyName)
        {
            ICacheStrategy _instance;
            string rootPath = string.Empty;

            try
            {
                //if web application
                rootPath = HttpRuntime.BinDirectory;
            }
            catch
            {
                //if remoting application
                rootPath = string.Empty;
            }

            Assembly assembly = Assembly.LoadFrom(rootPath + assemblyName);
            _instance = assembly.CreateInstance(typeName) as ICacheStrategy;

            return _instance;
        }
    }
}
